package com.example.shaketest;

import java.io.IOException;
import java.security.Key;
import java.security.SecureRandom;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

import sun.util.resources.TimeZoneNames;
import sun.util.resources.TimeZoneNames_zh_CN;

import android.app.Activity;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.RelativeLayout;

public class MainActivity extends Activity implements SensorEventListener,AnimationListener{
    /** Called when the activity is first created. */
    static String DES = "DES";
    private SensorManager sMan;
    private Sensor sensor;
    private Animation topInAnim = null;
    private Animation topOutAnim = null;
    private Animation botInAnim = null;
    private Animation botOutAnim = null;
    private int duration =630;
    private ImageView ivTop;
    private ImageView ivBot;
    //啦啦啦
    private ImageView shake_bg;
    
    private ImageView shake_line_up;
    private ImageView shake_line_down;
    
    private RelativeLayout shake_panel_up;
    private RelativeLayout shake_panel_down;
    
    private int scr_h,src_w;
    
    private MediaPlayer mPlayer;
    
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        scr_h = getWindowManager().getDefaultDisplay().getHeight();
        src_w = getWindowManager().getDefaultDisplay().getWidth();
        initSensorManager();
        initViews();
        initAnim();
        initPlayer();
        
        desTest();
        timeTest();
    }
    
    private void timeTest() {
    	Log.i("11111", "时区"+TimeZone.getDefault().getDisplayName(false,TimeZone.SHORT));
    	
    	long time = System.currentTimeMillis()+
				( TimeZone.getTimeZone("GMT+08:00").getRawOffset()-TimeZone.getDefault().getRawOffset());
    	Calendar c = Calendar.getInstance();
    	c.setTime(new Date(time));
		Log.i("11111", "time is "+time+"\n"+c.get(Calendar.DAY_OF_WEEK)+"\n"+(int)((time/1000+3600*8)/(3600*24)));
    	
    	
    	c.setTimeZone(TimeZone.getTimeZone("GMT+08:00"));
    	c.setTime(new Date(System.currentTimeMillis()));
    			
	}

	private void desTest(){
    	String key = "12345678";
    	String data= "wangshengru";
    	try {
			Log.i("11111", "加密 "+encode(key, data));
			Log.i("11111", "解密 "+decode(key,encode(key, data)));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    
    /**
     * DES算法，加密
     * @param data 待加密字符串
     * @param key 加密私钥，长度不能够小于8位
     * @return 加密后的字节数组，一般结合Base64编码使用
     * @throws CryptException 异常
     */
    public static String encode(String key, String data) throws Exception {
     return encode(key, data.getBytes());
    }
    /**
     * DES算法，加密
     * @param data  待加密字符串
     * @param key  加密私钥，长度不能够小于8位
     * @return 加密后的字节数组，一般结合Base64编码使用
     * @throws CryptException
     *             异常
     */
    private static String encode(String key, byte[] data) throws Exception {
     try {
      DESKeySpec dks = new DESKeySpec(key.getBytes());
      SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
      // key的长度不能够小于8位字节
      Key secretKey = keyFactory.generateSecret(dks);
      Cipher cipher = Cipher.getInstance(DES);
      IvParameterSpec iv = new IvParameterSpec("12345678".getBytes());
      AlgorithmParameterSpec paramSpec = iv;
      cipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec);
      byte[] bytes = cipher.doFinal(data);
      return Base64.encodeToString(bytes, 0);
     } catch (Exception e) {
      throw new Exception(e);
     }
    }
    /**
     * DES算法，解密
     * @param data  待解密字符串
     * @param key 解密私钥，长度不能够小于8位
     * @return 解密后的字节数组
     * @throws Exception  异常
     */
    private static byte[] decode(String key, byte[] data) throws Exception {
     try {
      DESKeySpec dks = new DESKeySpec(key.getBytes());
      SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
      // key的长度不能够小于8位字节
      Key secretKey = keyFactory.generateSecret(dks);
      Cipher cipher = Cipher.getInstance(DES);
      IvParameterSpec iv = new IvParameterSpec("12345678".getBytes());
      AlgorithmParameterSpec paramSpec = iv;
      cipher.init(Cipher.DECRYPT_MODE, secretKey, paramSpec);
      return cipher.doFinal(data);
     } catch (Exception e) {
      throw new Exception(e);
     }
    }
    
    /**
     * 解密.
     * @param key
     * @param data
     * @return
     * @throws Exception
     */
    public static String decode(String key, String data) {
     byte[] datas;
     String value = null;
     try {
      if (System.getProperty("os.name") != null
        && (System.getProperty("os.name").equalsIgnoreCase("sunos") || System
          .getProperty("os.name").equalsIgnoreCase("linux"))) {
       datas = decode(key, Base64.decode(data, 0));
      } else {
       datas = decode(key, Base64.decode(data, 0));
      }
      value = new String(datas);
     } catch (Exception e) {
      value = "";
     }
     return value;
    }
  
    
    
    
    private  void initPlayer(){
        mPlayer = new MediaPlayer();
        //mPlayer.setDataSource(context, uri);
        AssetManager aMan = this.getAssets();
        try {
            AssetFileDescriptor  fileDescriptor = aMan.openFd("shake_sound_male.mp3");
            mPlayer.setDataSource(fileDescriptor.getFileDescriptor(),fileDescriptor.getStartOffset(),fileDescriptor.getLength());
            mPlayer.prepare();
            //mPlayer.start();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    private void initSensorManager(){
        
         sMan = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
         sensor = sMan.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
         sMan.registerListener(this, sensor,SensorManager.SENSOR_DELAY_NORMAL);
        
    }

    private void initAnim(){
        
        
        topOutAnim = new TranslateAnimation(0,0,0,-(float)scr_h/4);
        topOutAnim.setDuration(duration);
        topOutAnim.setInterpolator(new DecelerateInterpolator());
        
        botOutAnim = new TranslateAnimation(0,0,0,(float)scr_h/4);
        botOutAnim.setDuration(duration);
        botOutAnim.setInterpolator(new DecelerateInterpolator());
        
        topInAnim = new TranslateAnimation(0,0,-(float)scr_h/4,0);
        topInAnim.setDuration(duration);
        topInAnim.setInterpolator(new AccelerateInterpolator());
        
        botInAnim = new TranslateAnimation(0,0,(float)scr_h/4,0);
        botInAnim.setDuration(duration);
        botInAnim.setInterpolator(new AccelerateInterpolator());
        
        botInAnim.setAnimationListener(this);
        botOutAnim.setAnimationListener(this);
        
    }
    
    private void initViews(){
        
        
        shake_bg = (ImageView)findViewById(R.id.iv_hide);
        
        shake_panel_up = (RelativeLayout)findViewById(R.id.frameTop);
        shake_panel_down = (RelativeLayout)findViewById(R.id.frameBot);
        
        shake_line_up = (ImageView)findViewById(R.id.shake_line_up);
        shake_line_down = (ImageView)findViewById(R.id.shake_line_down);
        shake_line_up.setVisibility(View.INVISIBLE);
        shake_line_down.setVisibility(View.INVISIBLE);
        
        ivTop =  (ImageView)findViewById(R.id.ivTop);
        ivBot = (ImageView)findViewById(R.id.ivBot);
    }
    
    @Override
    public void onAnimationEnd(Animation arg0) {
        // TODO Auto-generated method stub
        if(arg0 == botOutAnim){//���Ŵ�
            shake_panel_up.startAnimation(topInAnim);
            shake_panel_down.startAnimation(botInAnim);
        }else if(arg0.equals(botInAnim)){//���Źر�
            Log.e("wn", "sdgsdg");
            sMan.registerListener(this, sensor,SensorManager.SENSOR_DELAY_NORMAL);
            shake_line_up.setVisibility(View.INVISIBLE);
            shake_line_down.setVisibility(View.INVISIBLE);
            shake_bg.setVisibility(View.INVISIBLE);
            //��ɶ������ٴμ��������
        }
    }

    @Override
    public void onAnimationRepeat(Animation animation) {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void onAnimationStart(Animation animation) {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        // TODO Auto-generated method stub
        float x = event.values[SensorManager.DATA_X];
        float y = event.values[SensorManager.DATA_Y];
        float z = event.values[SensorManager.DATA_Z];
        if(Math.abs(x)>=14||Math.abs(y)>=14||Math.abs(z)>=14){
            
            shake_line_up.setVisibility(View.VISIBLE);
            shake_line_down.setVisibility(View.VISIBLE);
            shake_bg.setVisibility(View.VISIBLE);
            mPlayer.start();
            shake_panel_up.startAnimation(topOutAnim);
            shake_panel_down.startAnimation(botOutAnim);
            sMan.unregisterListener(this);
        }
    }
    
    
}